from fastapi import APIRouter, Depends
from loguru import logger

from app.schemas.work_order import *
from app.schemas.flight_event import *
from app.schemas.response import DefaultResponse
from concurrent.futures import ThreadPoolExecutor
from app.services.work_order_service import report as work_order_report
from app.services.flight_record_service import report as patrol_report
router = APIRouter(prefix='/report')

_report_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix='report_worker')

def get_report_executor():
    return _report_executor

@router.post('/work-order', response_model=DefaultResponse)
async def work_order(work_order_detail: WorkOrderReport, executor: ThreadPoolExecutor = Depends(get_report_executor)):
    """处理工单报告接口

    Parameters
    ----------
    work_order_detail : WorkOrderReport
        工单报告详细信息，包含工单ID、状态等数据
    executor : ThreadPoolExecutor
        线程池执行器，用于异步处理任务
    """
    # logger.info(f'[web-task] handle report work_order')
    def background_task():
        
        try:
            work_order_report(work_order_detail)
        except Exception as e:
            logger.error(f"Error in background task: {e}", exc_info=True)

    executor.submit(background_task)
    return DefaultResponse()


@router.post('/patrol', response_model=DefaultResponse)
async def patrol(patrol_detail: PatrolReport, executor: ThreadPoolExecutor = Depends(get_report_executor)):
    """处理巡检报告接口

    Parameters
    ----------
    patrol_detail : PatrolReport
        巡检报告详细信息，包含巡检任务ID、状态等数据
    executor : ThreadPoolExecutor
        线程池执行器，用于异步处理任务
    """
    # logger.info(f'[web-task] handle report patrol, request:{patrol_detail.model_dump()}')
    def background_task():
        try:
            patrol_report(patrol_detail)
        except Exception as e:
            logger.error(f"Error in background task: {e}", exc_info=True)

    executor.submit(background_task)
    return DefaultResponse()
